package com.arelikebrothers.demo.concurrent.begin;

/**
 * Created by lennon on 30/04/2017.
 * 使用中断来优化上面的停止线程方式
 */
public class StopThreadSafeUseInterrupt {
    public static User user = new User();

    public static class ChangeObjectThread extends Thread {

        @Override
        public void run() {
            while (true) {
                if (Thread.currentThread().isInterrupted()) {
                    System.out.println("Interrupted");
                    break;
                }

                synchronized (user) {
                    int v = (int) (System.currentTimeMillis() / 100);
                    user.setId(v);

                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        // 注意：Thread.sleep()方法由于中断而抛出异常，此时，他会清除中断标记，
                        // 如果不处理，那么在下一次循环开始时，就无法捕获这个中断，故在异常处理代码中，
                        // 再次设置中断标记位。
                        Thread.currentThread().interrupt();
                    }
                    user.setName(String.valueOf(v));
                }
                Thread.yield();
            }
        }
    }

    public static class ReadObjectThread extends Thread {
        @Override
        public void run() {
            while (true) {
                synchronized (user) {
                    if (user.getId() != Integer.parseInt(user.getName())) {
                        System.out.println(user);
                    }
                }
                Thread.yield();
            }
        }
    }

    public static void main(String[] args) {
        new ReadObjectThread().start();
        while (true) {
            ChangeObjectThread thread = new ChangeObjectThread();
            thread.start();
            try {
                Thread.sleep(150);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            thread.interrupt();
        }
    }
}


